<?php
/**
 * 跃飞科技版权所有 @2017
 * User: 钟贵廷
 * Date: 2017/5/17
 * Time: 16:26
 * 微信消息自动回复
 *
 */
namespace app\wechat\controller;
use app\admin\controller\Admin;
use app\admin\model\User;
use think\Request;

class Index extends Wechat
{
    /**
     * 微信入口
     * echoStr 用于token验证
     */
    public function index()
    {
        $echoStr =  Request::instance()->get('echostr');
        if($this->checkSignature())
        {
            if($echoStr)
            {
                echo $echoStr;
            }
            else
            {
                $this->responseMsg();
            }
            exit;
        }
    }

    /**
     * 微信验证方法
     * @return bool
     */
    private function checkSignature()
    {
        if (!defined("TOKEN"))
        {
            throw new \Exception('TOKEN尚未定义');
        }
        $signature = Request::instance()->get('signature');
        $timestamp = Request::instance()->get('timestamp');
        $nonce = Request::instance()->get('nonce');
        $token = TOKEN;
        $tmpArr = array($token, $timestamp, $nonce);
        sort($tmpArr, SORT_STRING);
        $tmpStr = implode( $tmpArr );
        $tmpStr = sha1( $tmpStr );
        if( $tmpStr == $signature )
        {
            return true;
        }
        else
        {
            return false;
        }
    }

    /**
     * 响应数据
     */
    public function responseMsg()
    {
        $postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
        if (!empty($postStr))
        {
            libxml_disable_entity_loader(true);
            $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
            log_output($postObj);
            $msgType = $postObj->MsgType;
            if($msgType == 'text')
            {
                $content = '我是跃飞，欢迎你关注我,更多了解请访问我的网站http://w.url.cn/s/AhQjkLF';
                $this->responseTextMsg($postObj,$content);
            }
            elseif($msgType == 'image')
            {
                $this->responseImageMsg($postObj);
            }
            elseif ($msgType == 'event')
            {
                if(!empty($postObj->EventKey))
                {
                    if ($postObj->Event == 'SCAN')
                    {
                        $this->responseScanMsg($postObj);
                    }
                }
                if($postObj->Event == 'subscribe')  //订阅
                {
                    $userModel =  new User();
                    $userModel->add($postObj);
                    $this->responseSubscribeMsg($postObj);
                }
                elseif ($postObj->Event == 'unsubscribe') //取消订阅
                {
                    //删除用户
                    $userModel =  new User();
                    $postObj = (array)$postObj;
                    $userModel->where(['username'=>$postObj['FromUserName']])->delete();
                }
            }
        }
        else
        {
            echo "";
            exit;
        }
    }

//    回复文本消息
    private function responseTextMsg($postObj,$content)
    {
        $textTpl = "<xml>
                        <ToUserName><![CDATA[%s]]></ToUserName>
                        <FromUserName><![CDATA[%s]]></FromUserName>
                        <CreateTime>%s</CreateTime>
                        <MsgType><![CDATA[%s]]></MsgType>
                        <Content><![CDATA[%s]]></Content>
                        <FuncFlag>0</FuncFlag>
                        </xml>";
        $resultStr = sprintf($textTpl, $postObj->FromUserName, $postObj->ToUserName, time(), 'text', $content);
        echo $resultStr;
    }

    //回复图片消息
    private function responseImageMsg($postObj)
    {
        $textTpl = "<xml>
                        <ToUserName><![CDATA[%s]]></ToUserName>
                        <FromUserName><![CDATA[%s]]></FromUserName>
                        <CreateTime>%s</CreateTime>
                        <MsgType><![CDATA[%s]]></MsgType>
                        <Content><![CDATA[%s]]></Content>
                        <FuncFlag>0</FuncFlag>
                        </xml>";
        $resultStr = sprintf($textTpl, $postObj->FromUserName, $postObj->ToUserName, time(), 'text', '不要发图片');
        echo $resultStr;
    }


    private function responseSubscribeMsg($postObj)
    {
        $textTpl = "<xml>
                        <ToUserName><![CDATA[%s]]></ToUserName>
                        <FromUserName><![CDATA[%s]]></FromUserName>
                        <CreateTime>%s</CreateTime>
                        <MsgType><![CDATA[%s]]></MsgType>
                        <Content><![CDATA[%s]]></Content>
                        <FuncFlag>0</FuncFlag>
                        </xml>";
        $resultStr = sprintf($textTpl, $postObj->FromUserName, $postObj->ToUserName, time(), 'text', '谢谢关注');
        echo $resultStr;
    }

    private function responseScanMsg($postObj)
    {
        $textTpl = "<xml>
                        <ToUserName><![CDATA[%s]]></ToUserName>
                        <FromUserName><![CDATA[%s]]></FromUserName>
                        <CreateTime>%s</CreateTime>
                        <MsgType><![CDATA[%s]]></MsgType>
                        <Content><![CDATA[%s]]></Content>
                        <FuncFlag>0</FuncFlag>
                        </xml>";
        $resultStr = sprintf($textTpl, $postObj->FromUserName, $postObj->ToUserName, time(), 'text', '你已经关注过我拉');
        echo $resultStr;
    }


    private function responseUnSubscribeMsg($postObj)
    {
        $textTpl = "<xml>
                        <ToUserName><![CDATA[%s]]></ToUserName>
                        <FromUserName><![CDATA[%s]]></FromUserName>
                        <CreateTime>%s</CreateTime>
                        <MsgType><![CDATA[%s]]></MsgType>
                        <Content><![CDATA[%s]]></Content>
                        <FuncFlag>0</FuncFlag>
                        </xml>";
        $resultStr = sprintf($textTpl, $postObj->FromUserName, $postObj->ToUserName, time(), 'text', '欢迎下次关注我哦');
        echo $resultStr;
    }


    /**
     * 测试使用
     */
    public function test()
    {
        $textTpl = "<xml>
							<ToUserName><![CDATA[%s]]></ToUserName>
							<FromUserName><![CDATA[%s]]></FromUserName>
							<CreateTime>%s</CreateTime>
							<MsgType><![CDATA[%s]]></MsgType>
							<Content><![CDATA[%s]]></Content>
							<FuncFlag>0</FuncFlag>
							</xml>";
        $postStr = sprintf($textTpl, 'fdsfdsf', 'fdsfsafxx', time(), 'text','aaaaaaaaaaaaa');
        libxml_disable_entity_loader(true);
        $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
        p($postObj);
        p($postObj->MsgType);
//        $postArr = (array)$postObj;
//        p((array)$postObj);
//        p($postArr['MsgType']);
    }


    public function test2()
    {
        $user = new User();
        $user->info('m0LfXqyHg5aGYIQazSCnq4Bfg6FrF-mj2JbU_bIT8Wuehs2SNnTikuINmpZot58sQtAfdoNBzJ8-WM6cVI-00UIO4rdXbpah8YYPWuLp4DHeLxYSph1NDaKxnlIY-qYlSNXjAHAHCM', 'oZYXqjjufrUPXtEOvuiImGijgaDk');
    }

}